﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.SharePoint;

//requires References to:
//1. AzureConnect
//2. Microsoft.SharePoint
//3. System.ServiceModel
//4. System.Runtime.Serialization
//5. System.Web

namespace AzureWcfPage
{
    public class WcfDataControl : AzureConnect.WcfConfig
    {

        //this method must be overridden so the proxy can be configured and created correctly
        public override bool ExecuteRequest()
        {
            try
            {
                //create the proxy instance using the bindings and endpoint the base class
                //configuration control has created for this
                CustomersWCF.CustomersClient cust =
                    new CustomersWCF.CustomersClient(this.FedBinding, this.WcfEndpointAddress);

                //configure the channel so we can call it with FederatedClientCredentials. 
                SPChannelFactoryOperations.ConfigureCredentials<CustomersWCF.ICustomers>
                    (cust.ChannelFactory, Microsoft.SharePoint.SPServiceAuthenticationMode.Claims);

                //create a channel to the WCF endpoint using the token and claims of the current user
                CustomersWCF.ICustomers claimsWCF =
                    SPChannelFactoryOperations.CreateChannelActingAsLoggedOnUser
                    <CustomersWCF.ICustomers>(cust.ChannelFactory, this.WcfEndpointAddress,
                    new Uri(this.WcfEndpointAddress.Uri.AbsoluteUri));

                //set the client property for the base class
                this.WcfClientProxy = claimsWCF;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
                
            //now that the configuration is complete, call the method
            return base.ExecuteRequest();
        }

    }
}
